package my.epoll;

import my.common.Errors;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author fengbo
 */
public class Native {

    public static final int EPOLLIN = epollin();
    public static final int EPOLLOUT = epollout();
    public static final int EPOLLRDHUP = epollrdhup();
    public static final int EPOLLET = epollet();
    public static final int EPOLLERR = epollerr();

    public static int epollCreate() {
        return epollCreate0();
    }

    private static native int epollCreate0();

    public static int timerCreate() {
        return timerCreate0();
    }
    private static native int timerCreate0();

    public static int eventCreate() {
        return eventCreate0();
    }
    private static native int eventCreate0();
    public static native void eventFdWrite(int fd, long value);
    public static native void eventFdRead(int fd);

    public static void epollCtlAdd(int efd, final int fd, final int flags) throws IOException {
        int res = epollCtlAdd0(efd, fd, flags);
        if (res < 0) {
            throw Errors.newIOException("epoll_ctl", res);
        }
    }
    private static native int epollCtlAdd0(int efd, final int fd, final int flags);

    public static void epollCtlMod(int efd, final int fd, final int flags) throws IOException{
        int res = epollCtlMod0(efd, fd, flags);
        if (res < 0) {
            throw Errors.newIOException("epoll_ctl", res);
        }
    }
    private static native int epollCtlMod0(int efd, final int fd, final int flags);

    public static void epollCtlDel(int efd, final int fd) throws IOException {
        int res = epollCtlDel0(efd, fd);
        if (res < 0) {
            throw Errors.newIOException("epoll_ctl", res);
        }
    }
    private static native int epollCtlDel0(int efd, final int fd);

    public static int epollWait(int efd, EventArray events, int tfd) throws IOException {
        int ready = epollWait0(efd, events.memoryAddress(), events.length(), tfd, 1, 0);
        if (ready < 0) {
            throw Errors.newIOException("epoll_wait", ready);
        }
        return ready;
    }
    private static native int epollWait0(int efd, long address, int len, int tfd, int sec, int ns);

    private static native int epollin();
    private static native int epollout();
    private static native int epollrdhup();
    private static native int epollet();
    private static native int epollerr();


    /** epoll_event related */
    public static native int sizeofEpollEvent();
    public static native int offsetofEpollData();

    public static native long memoryAddress(ByteBuffer buffer);
}
